/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-10-19  @author lizhen
 */

package kubernetes

import (
	"github.com/json-iterator/go"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/client-go/kubernetes"
)

var (
	zero   = initZero()
	option = initOption()
)

func DeleteDeployment(client kubernetes.Interface, namespace, name string) (err error) {
	errs := make([]error, 0, 3)
	deploy, e := client.AppsV1().Deployments(namespace).Patch(name, types.StrategicMergePatchType, zero)
	if e != nil {
		errs = append(errs, e)
	}
	if e := client.AppsV1().ReplicaSets(namespace).DeleteCollection(
		option, metav1.ListOptions{
			LabelSelector: labels.SelectorFromSet(labels.Set(deploy.Labels)).String()}); e != nil {
		errs = append(errs, e)
	}
	if e := client.AppsV1().Deployments(namespace).Delete(name, option); e != nil {
		errs = append(errs, e)
	}
	if count := len(errs); count == 1 {
		err = errs[0]
	} else if count > 1 {
		err = errors.NewAggregate(errs)
	}
	return
}

func initZero() (content []byte) {
	z := new(struct {
		Spec struct {
			Replicas int `json:"replicas"`
		} `json:"spec"`
	})
	z.Spec.Replicas = 0
	var err error
	if content, err = jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(z); err != nil {
		panic(err)
	}
	return
}

func initOption() (do *metav1.DeleteOptions) {
	orphan := metav1.DeletePropagationOrphan
	do = &metav1.DeleteOptions{PropagationPolicy: &orphan}
	return
}
